import requests
import socket
from netifaces import interfaces, ifaddresses, AF_INET


class MyIp:
    def __init__(self):
        self.value = ""

    def extract_ip(self):
        st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            st.connect(('10.255.255.255', 1))
            IP = st.getsockname()[0]
        except Exception:
            IP = '127.0.0.1'
        finally:
            st.close()
        return IP

    # 主逻辑
    def get_ip(self):
        try:
            if self.value == None or "" or " ":
                # 通过网站获取ip
                value_request = requests.get('http://myip.ipip.net', timeout=5).text
                self.value = value_request
                print(f"第一次尝试获取ip：{self.value}")
                return self.value
            else:
                if self.value == None or "" or " ":
                    # 函数 gethostname() 返回当前正在执行 Python 的系统主机名
                    value_host = socket.gethostbyname(socket.gethostname())
                    self.value = value_host
                    print(f"第二次尝试获取ip：{self.value}")
                    return self.value
                else:
                    if self.value == None or "" or " ":
                        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                        s.connect(("8.8.8.8", 80))
                        self.value = s.getsockname()[0]
                        print(f"第三次尝试获取ip：{self.value}")
                        return self.value
                    else:
                        if self.value == None or "" or " ":
                            self.value = self.extract_ip()
                            print(f"第四次尝试获取ip：{self.value}")
                            return self.value
                        else:
                            if self.value == None or "" or " ":
                                for ifaceName in interfaces():
                                    addresses = [i['addr'] for i in
                                                 ifaddresses(ifaceName).setdefault(AF_INET, [{'addr': 'No IP addr'}])]
                                    self.value = ' '.join(addresses)
                                    print(f"第五次尝试获取ip：{self.value}")
                                    return self.value
        except Exception as e:
                print(f"第六次尝试获取ip：{self.value}")
                msg = "未知错误，没有获取到ip"
                print(msg)
        finally:
            print(f"最终获取到的ip:{self.value}")

if __name__ == '__main__':
    ip = MyIp()
    ip.get_ip()
